"""
生成器：
优点：可以节省内存
缺点：惰性求值，只能取一次值，不能使用索引，必须逐个取值

写法：元组推导式、函数是写法（yield）

"""

from collections.abc import Generator


# datas1 = [i for i in range(10000)]
# print(isinstance(datas1, list), datas1.__sizeof__(), datas1[500])
#
# datas2 = (i for i in range(10000))
# print(isinstance(datas2, Generator),  datas2.__sizeof__())

# 只能逐个取值
# print(next(datas2))
# print(next(datas2))

# for data2 in datas2:
# 	print(data2)
# # 只能取值一次
# for data2 in datas2:
# 	print(data2)


def my_fun():
    yield 10
    yield 20
    return 100, 200


r = my_fun()
# print(type(r))

try:
    while True:
        print(next(r))
except StopIteration as e:
    print(f"迭代异常{e}")
except Exception as e:
    print(f"未知异常{e}")

